package com.itaem.crazy.shirodemo.common;

import com.alibaba.fastjson.JSONObject;
import com.itaem.crazy.shirodemo.modules.shiro.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/***
 * 捕获全局错误处理类
 */
@RestControllerAdvice
public class GlobalExceptionHandle {


    @ExceptionHandler(ShiroException.class)   ////捕捉所有的shiro报错类
    //@ExceptionHandler(value = AuthorizationException.class)   //捕捉单独的shiro报错类
    public Object ShiroExceptionHandler(@org.jetbrains.annotations.NotNull ShiroException se) {
        Subject subject =SecurityUtils.getSubject();
        JSONObject jsonObject = new JSONObject();
        String msg="";
        jsonObject.put("success",false);
        jsonObject.put("state","400");
        se.printStackTrace();  //控制台打印捕捉到的错误
        if(se instanceof IncorrectCredentialsException) {
            msg = "登录密码错误. Password for account " + subject.getPrincipal() + " was incorrect.";
        }
        else if(se instanceof ExcessiveAttemptsException) {
            msg = "登录失败次数过多";
        }
        else if(se instanceof LockedAccountException) {
            msg = "帐号已被锁定. The account for username " + subject.getPrincipal() + " was locked.";
        }
        else if(se instanceof DisabledAccountException) {
            msg = "帐号已被禁用. The account for username " + subject.getPrincipal() + " was disabled.";
        }
        else if(se instanceof ExpiredCredentialsException) {
            msg = "帐号已过期. the account for username " + subject.getPrincipal() + "  was expired.";
        }
        else if(se instanceof UnknownAccountException) {
            msg = "帐号不存在. There is no user with username of " + subject.getPrincipal();
        }
        else if(se instanceof UnauthorizedException) {  //或者使用AuthorizationException都可以
            msg = "您没有得到相应的授权！" + se.getMessage();
        }
        else {
            msg = "登录失败";
        }
        jsonObject.put("msg",msg);
        return jsonObject;
    }



    // 捕捉其他所有异常
    @ExceptionHandler(Exception.class)
    public Object ExceptionHandler(HttpServletRequest request, Throwable ex) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("success",false);
        jsonObject.put("state","400");
        jsonObject.put("msg","系统异常！ 访问出错，无法访问: " + ex.getMessage());
        return jsonObject;
    }


}